/**
 * 订单详情页面组件
 * 展示单个订单的详细信息，包括商品、状态、金额、时间等
 */
import { View, Text, ScrollView, Button } from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import { useState, useEffect } from 'react'
import { useAppContext } from '../../store'
import { CloudDataManager } from '../../utils/cloud'
import { formatDateTime } from '../../utils'
import './detail.scss'

/**
 * 订单详情页面组件
 * 提供订单详细信息展示、状态更新、操作按钮等功能
 */
export default function OrderDetail() {
  const router = useRouter()
  const { state } = useAppContext()
  
  // 订单详情数据
  const [order, setOrder] = useState<any>(null)
  // 加载状态
  const [loading, setLoading] = useState(true)
  // 操作按钮加载状态
  const [actionLoading, setActionLoading] = useState(false)

  /**
   * 组件挂载时加载订单详情
   */
  useEffect(() => {
    if (router.params.id) {
      loadOrderDetail(router.params.id)
    }
  }, [router.params.id])

  /**
   * 加载订单详情数据
   * @param orderId 订单ID
   */
  const loadOrderDetail = async (orderId: string) => {
    try {
      setLoading(true)
      
      // 从云数据库获取订单详情
      const orderData = await CloudDataManager.getData('orders', orderId)
      
      if (orderData) {
        setOrder(orderData)
      } else {
        Taro.showToast({
          title: '订单不存在',
          icon: 'error'
        })
        Taro.navigateBack()
      }
    } catch (error) {
      console.error('加载订单详情失败:', error)
      Taro.showToast({
        title: '加载失败',
        icon: 'error'
      })
    } finally {
      setLoading(false)
    }
  }

  /**
   * 获取订单状态的中文显示文本
   * @param status 订单状态
   * @returns string 状态中文文本
   */
  const getStatusText = (status: string) => {
    const statusMap = {
      pending: '待确认',
      confirmed: '已确认',
      completed: '已完成',
      cancelled: '已取消'
    }
    return statusMap[status] || status
  }

  /**
   * 获取订单状态对应的颜色
   * @param status 订单状态
   * @returns string 颜色值
   */
  const getStatusColor = (status: string) => {
    const colorMap = {
      pending: '#ff9500',
      confirmed: '#007aff',
      completed: '#34c759',
      cancelled: '#ff3b30'
    }
    return colorMap[status] || '#999'
  }

  /**
   * 获取订单ID的短格式（微信小程序兼容）
   * @param orderId 完整订单ID
   * @returns string 短格式订单ID
   */
  const getShortOrderId = (orderId: string) => {
    if (orderId.length <= 8) return orderId
    return orderId.substring(orderId.length - 8)
  }

  /**
   * 处理订单状态更新
   * @param newStatus 新状态
   */
  const handleStatusUpdate = async (newStatus: string) => {
    if (!order) return
    
    try {
      setActionLoading(true)
      
      // 更新订单状态
      await CloudDataManager.updateData('orders', order.id, {
        status: newStatus,
        updatedAt: new Date()
      })
      
      // 重新加载订单详情
      await loadOrderDetail(order.id)
      
      Taro.showToast({
        title: '状态更新成功',
        icon: 'success'
      })
    } catch (error) {
      console.error('更新订单状态失败:', error)
      Taro.showToast({
        title: '更新失败',
        icon: 'error'
      })
    } finally {
      setActionLoading(false)
    }
  }

  /**
   * 处理订单取消
   */
  const handleCancelOrder = () => {
    Taro.showModal({
      title: '确认取消',
      content: '确定要取消这个订单吗？',
      success: (res) => {
        if (res.confirm) {
          handleStatusUpdate('cancelled')
        }
      }
    })
  }

  /**
   * 处理订单确认
   */
  const handleConfirmOrder = () => {
    handleStatusUpdate('confirmed')
  }

  /**
   * 处理订单完成
   */
  const handleCompleteOrder = () => {
    handleStatusUpdate('completed')
  }

  /**
   * 返回上一页
   */
  const handleBack = () => {
    Taro.navigateBack()
  }

  if (loading) {
    return (
      <View className='order-detail'>
        <View className='loading-container'>
          <Text className='loading-text'>加载中...</Text>
        </View>
      </View>
    )
  }

  if (!order) {
    return (
      <View className='order-detail'>
        <View className='error-container'>
          <Text className='error-text'>订单不存在</Text>
          <Button className='back-btn' onClick={handleBack}>
            返回
          </Button>
        </View>
      </View>
    )
  }

  return (
    <View className='order-detail'>
      {/* 页面头部 */}
      <View className='header'>
        <Button className='back-button' onClick={handleBack}>
          返回
        </Button>
        <Text className='title'>订单详情</Text>
      </View>

      {/* 订单信息 */}
      <ScrollView className='order-content' scrollY>
        {/* 订单基本信息 */}
        <View className='order-info'>
          <View className='order-header'>
            <Text className='order-id'>订单 #{getShortOrderId(order.id)}</Text>
            <Text 
              className='order-status'
              style={{ color: getStatusColor(order.status) }}
            >
              {getStatusText(order.status)}
            </Text>
          </View>
          
          <View className='order-time'>
            <Text className='time-label'>下单时间：</Text>
            <Text className='time-value'>{formatDateTime(order.createdAt)}</Text>
          </View>
          
          {order.updatedAt && order.updatedAt !== order.createdAt && (
            <View className='order-time'>
              <Text className='time-label'>更新时间：</Text>
              <Text className='time-value'>{formatDateTime(order.updatedAt)}</Text>
            </View>
          )}
        </View>

        {/* 订单商品列表 */}
        <View className='order-items'>
          <Text className='section-title'>商品信息</Text>
          {order.items.map((item: any, index: number) => (
            <View key={index} className='item-row'>
              <View className='item-info'>
                <Text className='item-name'>{item.dishName || item.name}</Text>
                <Text className='item-price'>¥{item.price}</Text>
              </View>
              <Text className='item-quantity'>x{item.quantity}</Text>
              <Text className='item-total'>¥{(item.price * item.quantity).toFixed(2)}</Text>
            </View>
          ))}
        </View>

        {/* 订单金额信息 */}
        <View className='order-amount'>
          <Text className='section-title'>金额信息</Text>
          <View className='amount-row'>
            <Text className='amount-label'>商品总额：</Text>
            <Text className='amount-value'>¥{order.totalAmount.toFixed(2)}</Text>
          </View>
          
          {order.pointsUsed && order.pointsUsed > 0 && (
            <View className='amount-row'>
              <Text className='amount-label'>积分抵扣：</Text>
              <Text className='amount-value discount'>-¥{(order.pointsUsed / 100).toFixed(2)}</Text>
            </View>
          )}
          
          <View className='amount-row final'>
            <Text className='amount-label'>实付金额：</Text>
            <Text className='amount-value final-amount'>¥{order.finalAmount.toFixed(2)}</Text>
          </View>
        </View>

        {/* 订单备注 */}
        {order.note && (
          <View className='order-note'>
            <Text className='section-title'>订单备注</Text>
            <Text className='note-content'>{order.note}</Text>
          </View>
        )}
      </ScrollView>

      {/* 操作按钮 */}
      <View className='action-buttons'>
        {order.status === 'pending' && (
          <>
            <Button 
              className='action-btn confirm-btn'
              disabled={actionLoading}
              onClick={handleConfirmOrder}
            >
              确认订单
            </Button>
            <Button 
              className='action-btn cancel-btn'
              disabled={actionLoading}
              onClick={handleCancelOrder}
            >
              取消订单
            </Button>
          </>
        )}
        
        {order.status === 'confirmed' && (
          <Button 
            className='action-btn complete-btn'
            disabled={actionLoading}
            onClick={handleCompleteOrder}
          >
            完成订单
          </Button>
        )}
      </View>
    </View>
  )
} 